//
//  WCBDataHelper.m
//  WeChatHelper
//
//  Created by Guo Rui on 2017/12/12.
//  Copyright © 2017年 TimeFace. All rights reserved.
//

#import "WCBDataHelper.h"
#import "WCASessionManager.h"
//#import "ContactsDataLogicDelegate-Protocol.h"
//#import "TFToast.h"
#import "NSDate+TFCore.h"

#import "WCBRegionModel.h"

static NSString * const kWCBBusinessCodeKey = @"kWCBBusinessCodeKey";
static NSString * const kWCBUserModelArchiverKey = @"kWCBUserModelArchiverKey";
static NSString * const kWCBUserModelSaveFileName = @"kWCBUserModelSaveFileName";

// 区域信息存储的文件名称
#define kWCBRegionPath  @"kWCBRegionPath.plist"
// 上次请求地区列表的时间
#define kLastRegionTime @"kLastRegionTime"
// 上次请求 与  本次请求的时间间隔最大值（超过这个时间就需要重新请求）
#define kRegionTimeOut  (60*60*24*7)

@interface WCBDataHelper()
@property (strong, nonatomic) NSArray *contactArray;

@property (strong, nonatomic) NSMutableDictionary *dataDateDict;
@end

@implementation WCBDataHelper
@synthesize buniessCode = _buniessCode;

+ (instancetype)sharedHelper {
    static WCBDataHelper *config = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        config = [[WCBDataHelper alloc] init];
    });
    
    return config;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.buniessCode = [[NSUserDefaults standardUserDefaults] objectForKey:kWCBBusinessCodeKey];
//        ContactsDataLogic *dataLogic = [[objc_getClass("ContactsDataLogic") alloc] initWithScene:0 delegate:self sort:1 extendChatRoom:0];
//        self.contactArray = [dataLogic getAllContacts];
        

        //1 判断是否有地区的plist
        NSArray *regionArray = [self getAllRegionArray];
        // 上次请求的时间
        NSString *str =[[NSUserDefaults standardUserDefaults] objectForKey: kLastRegionTime];
        NSTimeInterval lasttime =  [str floatValue];
        // 当前时间
        NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
        if (regionArray.count == 0 ||
            currentTime > lasttime + kRegionTimeOut)
        {
            //2 如果本地没有存储 || 上次请求时间和这次请求时间的间隔超过的kRegionTimeOut
            //就需要请求接口获得并存储到plist文件中
            NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
            NSString *fullPath = [cachesPath stringByAppendingPathComponent:kWCBRegionPath];
            [self p_requestRegionDataWithSavePath:fullPath];
        }
        
        self.dataDateDict = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    return self;
}

#pragma mark - Public
//- (CContact *)selfContact
//{
//    CContactMgr *contactMgr = [[objc_getClass("MMServiceCenter") defaultCenter] getService:objc_getClass("CContactMgr")];
//    return [contactMgr getSelfContact];
//}
//
//- (CContact *)filterContactWithDisplayName:(NSString *)displayName {
//
//    for (CContact *c in self.contactArray) {
//        NSLog(@"m_nsAliasName - %@", c.m_nsAliasName);
//        if ([c.m_nsAliasName isEqualToString:displayName]) {
//            return c;
//        }
//
//        NSLog(@"m_nsUsrName - %@", c.m_nsUsrName);
//        if ([c.m_nsUsrName isEqualToString:displayName]) {
//            return c;
//        }
//    }
//
//    return nil;
//}
//
//#pragma mark - <ContactsDataLogicDelegate>
//- (_Bool)onFilterContactCandidate:(CContact *)arg1 {
//    NSLog(@"**** %@", arg1);
//    return YES;
//}
//- (void)onContactsDataChange {
//    NSLog(@"onContactsDataChange");
//}

#pragma mark - Public
- (void)setBuniessCode:(NSString *)buniessCode
{
    _buniessCode = buniessCode;
    [self setUserDefaultsObject:buniessCode forKey:kWCBBusinessCodeKey];
}

- (NSString *)buniessCode
{
    _buniessCode = [[NSUserDefaults standardUserDefaults] objectForKey:kWCBBusinessCodeKey];
    return _buniessCode;
}

- (void)setUserDefaultsObject:(id)objc forKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:objc forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)saveUserModel:(UserModel *)userModel{
    
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:userModel forKey:kWCBUserModelArchiverKey];
    [archiver finishEncoding];

    // 获得usermodle 存储的路径
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *fullPath = [cachesPath stringByAppendingPathComponent:kWCBUserModelSaveFileName];
    // 写数据
    [data writeToFile:fullPath atomically:YES];
    
}

- (UserModel *)getCurrentUserModel{
    // 获得userModel 存储的路径
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *fullPath = [cachesPath stringByAppendingPathComponent:kWCBUserModelSaveFileName];
    NSData *data = [[NSMutableData alloc]initWithContentsOfFile:fullPath];
    // 读数据
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    UserModel *userModel = [unArchiver decodeObjectForKey:kWCBUserModelArchiverKey];
    return userModel;
}

- (NSArray *)getAllRegionArray{
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *fullPath = [cachesPath stringByAppendingPathComponent:kWCBRegionPath];
    NSArray *regionArray = [NSArray arrayWithContentsOfFile:fullPath];
    return regionArray;
}

-(NSArray *)getCityRegionArray:(NSInteger)pid{
    NSMutableArray *cityArray = [NSMutableArray array];

    NSArray *allRegionArray = [self getAllRegionArray];
    for (NSDictionary *dic in allRegionArray) {
        if ([dic[@"locationPid"] integerValue] == pid) {
            WCBRegionModel *regionModel = [WCBRegionModel modelWithDict:dic];
            regionModel.hasChild = [self p_checkHasChild:regionModel.locationId regionList:allRegionArray];
            [cityArray addObject:regionModel];
        }
    }
    return cityArray;
}
-(NSString *)getAdressForRegionMdoel:(WCBRegionModel *)regionModel{
    
    WCBRegionModel *pRegionModel;
    NSString *adressString = regionModel.locationName;
    // 做多只有4层地区层级
    for (NSInteger i = 0; i<4; i++) {
        pRegionModel =  [self p_findParentCity:regionModel];
//        if ([pRegionModel.locationName isEqualToString: regionModel.locationName])
//        {
//          // 直辖市 不需要拼接字符串
//        }
//        else
        {
            adressString = [NSString stringWithFormat:@"%@%@",pRegionModel.locationName,adressString];
        }
        regionModel = pRegionModel;
        if (pRegionModel.locationPid == 0)
        {
            return adressString;
        }
    }
    
    return nil;
}

- (NSArray <WCBRegionModel *>*)getAdressArrayForRegionModel:(WCBRegionModel *)regionModel{
    NSMutableArray *pRegionModelArray = [NSMutableArray array];
    [pRegionModelArray addObject:regionModel];
     WCBRegionModel *pRegionModel;
    for (NSInteger i = 0; i < 4; i++) {
        pRegionModel = [self p_findParentCity:regionModel];
        if (pRegionModel) {
            [pRegionModelArray addObject:pRegionModel];
            regionModel = pRegionModel;
            if (pRegionModel.locationId == 0) {
                break;
            }
        }
        
    }
    return pRegionModelArray;
}
#pragma mark - private

/**
 请求地区信息
 */
- (void)p_requestRegionDataWithSavePath:(NSString *)fullPath{
    [WCASessionManager POST:@"tfmobile/member/locationList"
                 parameters:@{@"isGzip" : @"0"}
                    success:^(NSURLSessionDataTask *task, id responseObject) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if ([[responseObject objectForKey:@"status"] boolValue])
                            {
                                NSArray *regionDicArray = [responseObject objectForKey:@"dataList"];
                                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                    [regionDicArray writeToFile:fullPath atomically:YES];
                                });
                            }
                            else{
                                NSLog(@"%@",[responseObject objectForKey:@"info"]);
                            }
                        });
                        
                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                        NSLog(@"区域列表请求失败");
                    }];
    
}


- (BOOL)p_checkHasChild:(NSInteger)lid regionList:(NSArray *)regionList
{
    for(NSDictionary* entry in regionList)
    {
        NSInteger locationPid = [entry[@"locationPid"] integerValue];
        if(locationPid == lid)
        {
            return YES;
        }
    }
    return NO;
}


/**
 找到currentRegionModel 的父级
 */
- (WCBRegionModel *)p_findParentCity:(WCBRegionModel *)currentRegionModel{
    NSArray *regionArray = [self getAllRegionArray];
    WCBRegionModel *pRegionModel = nil;
    for (NSDictionary *entry in regionArray) {
        WCBRegionModel *tempRegionModel = [WCBRegionModel modelWithDict:entry];
        // 找到了regionModel 的父级
        if (tempRegionModel.locationId == currentRegionModel.locationPid) {
            pRegionModel = tempRegionModel;
            break;
        }
    }
     return pRegionModel;
}




// ********************* 对扫描出的数据进行日期分析
- (void)beginAnalyse:(NSArray<WCAWeChatTimelineModel *> *)modelArray
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        for (WCAWeChatTimelineModel *model in modelArray) {
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:model.date.floatValue / 1000];
            NSString *year = [NSString stringWithFormat:@"%zd", date.tf_year];
            
            if (![self.dataDateDict.allKeys containsObject:year]) {
                NSMutableSet *set = [NSMutableSet set];
                [set addObject:[NSString stringWithFormat:@"%zd-%02d", date.tf_year, date.tf_month]];
                [self.dataDateDict setObject:set forKey:year];
            }
            else {
                NSMutableSet *set = [self.dataDateDict objectForKey:year];
                [set addObject:[NSString stringWithFormat:@"%zd-%02d", date.tf_year, date.tf_month]];
            }
        }
    });
}

- (NSArray<NSString *> *)getAllYears
{
    NSArray *years = [self.dataDateDict allKeys];
    return [years sortedArrayUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString * _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
}

- (NSArray<NSString *> *)getAllMonths
{
    NSMutableArray *monthArray = [NSMutableArray arrayWithCapacity:0];
    for (NSSet *set in [self.dataDateDict allValues]) {
        for (NSString *month in set) {
            [monthArray addObject:month];
        }
    }
    
    return [monthArray sortedArrayUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString * _Nonnull obj2) {
        obj1 = [obj1 stringByReplacingOccurrencesOfString:@"-" withString:@""];
        obj2 = [obj2 stringByReplacingOccurrencesOfString:@"-" withString:@""];
        return [@(obj1.integerValue) compare:@(obj2.integerValue)];
    }];
}

@end
